var core = require('../../core/enocean.js');
var fs = require('fs');
var PATH_TEACHING = '/../../modules/stats/teachin.json';


var teachin = function(req, res) {

	var type = req.params.type;
	var validTypes = core.availableSensors;
	
	// Check if the type of sensor to teach is known
	if (validTypes.indexOf(type) != -1) {
		
		var teachableSensor = new Object();
		teachableSensor.date = new Date();
		teachableSensor.type = type;

		fs.writeFile(__dirname + PATH_TEACHING, JSON.stringify(teachableSensor), 'utf8', function (err) {

			if (err) throw err;
				
			// Now we wait for the backend to insert the sensor
			fs.watch(__dirname+PATH_TEACHING, function (event, filename) {
				if (event == 'change') {
					fs.readFile(__dirname + PATH_TEACHING, 'utf-8', function(error, data) {
							
						if (error) throw error;
						if (data == '{}\n') {
							// Everything was good !
							res.end('{"code":"OK"}\n');
						} else {
							// Something bad happened, maybe another teaching request while the previous one was still pending.
							res.end('{"code":"KO"}\n');
							
						}
					});
				}
			});
		});
	} else {
		res.end('{"code":"KO"}');
	}
}

module.exports.teachin = teachin;
